package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户身份信息（通过TokenService，它能正确处理Bearer前缀）
        com.zzyl.common.core.domain.model.LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            // 存入到ThreadLocal对象中供业务使用
            UserThreadLocal.set(loginUser.getUserId());
            return true;
        }

        // 如果TokenService无法获取用户信息，则尝试直接解析token
        String authorization = request.getHeader("authorization");
        if (StringUtils.isEmpty(authorization)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }

        // 处理Bearer token格式
        String token = authorization;
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 解析令牌
        Claims claims;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }

        if (ObjectUtil.isEmpty(claims)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }

        // 获取用户信息
        Long userId = MapUtil.get(claims, "userId", Long.class);
        if (userId == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }

        // 存入到ThreadLocal对象中
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
